<template>
<!-- 参合人员缴费明细管理 -->
  <div class="payment-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="农民姓名">
              <el-input
                v-model="searchForm.farmerName"
                placeholder="请输入农民姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="身份证号">
              <el-input
                v-model="searchForm.idCard"
                placeholder="请输入身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="缴费状态">
              <el-select v-model="searchForm.status" placeholder="请选择缴费状态">
                <el-option label="全部" value="" />
                <el-option label="已缴" value="1" />
                <el-option label="未缴" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">
              <i class="el-icon-search"></i> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh"></i> 重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增缴费记录
      </el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
      >
        <el-table-column prop="detailId" label="缴费ID" width="100" align="center" />
        
        <el-table-column prop="farmerId" label="农民ID" width="100" align="center" />
        
        <el-table-column prop="farmerName" label="农民姓名" width="120" align="center" />
        
        <el-table-column prop="idCard" label="身份证号" width="180" align="center">
          <template #default="{ row }">
            <span class="ellipsis" :title="row.idCard">{{ row.idCard }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="amount" label="缴费金额(元)" width="120" align="center">
          <template #default="{ row }">
            {{ row.amount ? row.amount.toLocaleString() : '0.00' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="缴费状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'success' : 'warning'" 
              :effect="row.status === 1 ? 'light' : 'dark'"
              size="small"
            >
              {{ row.status === 1 ? '已缴' : '未缴' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="paymentTime" label="缴费时间" width="180" align="center">
          <template #default="{ row }">
            {{ row.paymentTime ? formatDate(row.paymentTime) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button size="mini" type="success" plain @click="handlePay(row)" :disabled="row.status === 1">
              <i class="el-icon-coin"></i> 缴费
            </el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="700px" 
      :close-on-click-modal="false"
      :before-close="resetForm"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="农民ID" prop="farmerId">
              <el-input 
                type="number" 
                v-model.number="formData.farmerId" 
                placeholder="请输入农民ID"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="农民姓名" prop="farmerName">
              <el-input 
                v-model="formData.farmerName" 
                placeholder="请输入农民姓名"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input 
                v-model="formData.idCard" 
                placeholder="请输入身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="缴费金额" prop="amount">
              <el-input 
                type="number" 
                step="0.01" 
                v-model.number="formData.amount" 
                placeholder="请输入缴费金额"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="缴费状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">已缴</el-radio>
            <el-radio :label="0">未缴</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            <i class="el-icon-close"></i> 取消
          </el-button>
          <el-button type="primary" @click="submitForm">
            <i class="el-icon-check"></i> 确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { formatDate } from '@/utils/date';

export default {
  name: 'FarmerPaymentManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        farmerName: '',
        idCard: '',
        status: ''
      },
      
      // 表格数据
      tableData: [],
      loading: false,
      
      // 分页配置
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 对话框配置
      dialogVisible: false,
      dialogTitle: '新增缴费记录',
      formData: {
        detailId: null,
        farmerId: null,
        farmerName: '',
        idCard: '',
        amount: null,
        status: 0,
        paymentTime: null
      },
      
      // 表单验证规则
      formRules: {
        farmerId: [
          { required: true, message: '请输入农民ID', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        farmerName: [
          { required: true, message: '请输入农民姓名', trigger: 'blur' },
          { min: 2, message: '农民姓名至少2个字符', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入缴费金额', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' },
          { validator: (rule, value, callback) => {
              if (value && value <= 0) {
                callback(new Error('缴费金额必须大于0'));
              } else {
                callback();
              }
            }, trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择缴费状态', trigger: 'change' }
        ]
      }
    };
  },
  
  methods: {
    // 格式化日期
    formatDate(date, format = 'YYYY-MM-DD') {
      return formatDate(date, format);
    },
    
    // 获取数据列表
    fetchData() {
      this.loading = true;
      request.get('/farmerPaymentDetail/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
      })
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.pagination.total = res.data.total;
          } else {
            this.$message.error(res.message || '获取缴费记录列表失败');
          }
        })
        .catch(err => {
          console.error('获取缴费记录列表失败:', err);
          this.$message.error('加载缴费记录列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        farmerName: '',
        idCard: '',
        status: ''
      };
      this.handleSearch();
    },
    
    // 分页大小变更
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    
    // 当前页变更
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    
    // 新增缴费记录
    handleAdd() {
      this.dialogTitle = '新增缴费记录';
      this.resetForm();
      this.dialogVisible = true;
      
      // 设置默认值
      this.formData.status = 0; // 默认未缴费
    },
    
    // 编辑缴费记录
    handleEdit(row) {
      this.dialogTitle = '编辑缴费记录';
      this.formData = {
        ...row
      };
      this.dialogVisible = true;
    },
    
    // 缴费
    handlePay(row) {
      this.$confirm(`确认标记缴费记录「${row.farmerName} - ${row.amount}元」为已缴费状态吗？`, '提示', {
        type: 'warning',
        confirmButtonText: '确认缴费',
        cancelButtonText: '取消'
      })
        .then(() => {
          request.post(`/farmerPaymentDetail/pay/${row.detailId}`)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('缴费状态更新成功');
                this.fetchData();
              } else {
                this.$message.error(res.message || '缴费状态更新失败');
              }
            })
            .catch(err => {
              this.$message.error('缴费状态更新失败，请联系管理员');
              console.error('缴费状态更新接口异常:', err);
            });
        })
        .catch(() => {});
    },
    
    // 删除缴费记录
    handleDelete(row) {
      this.$confirm(`确认删除缴费记录「${row.farmerName} - ${row.amount}元」吗？`, '提示', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          request.post(`/farmerPaymentDetail/delete/${row.detailId}`)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('缴费记录删除成功');
                this.fetchData();
              } else {
                this.$message.error(res.message || '缴费记录删除失败');
              }
            })
            .catch(err => {
              this.$message.error('删除失败，请联系管理员');
              console.error('删除接口异常:', err);
            });
        })
        .catch(() => {});
    },
    
    // 提交表单
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;

        const isEdit = !!this.formData.detailId;
        const apiUrl = isEdit ? '/farmerPaymentDetail/update' : '/farmerPaymentDetail/create';
        
        // 处理 BigDecimal 类型字段（前端传输字符串避免精度丢失）
        const params = {
          ...this.formData,
          amount: this.formData.amount?.toString()
        };

        request.post(apiUrl, params)
          .then(res => {
            if (res.code === 200) {
              this.$message.success(`${this.dialogTitle}成功`);
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error(`${this.dialogTitle}失败: ${res.message}`);
            }
          })
          .catch(err => {
            console.error(`${this.dialogTitle}接口异常:`, err);
            this.$message.error(`${this.dialogTitle}失败，请检查参数或联系管理员`);
          });
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.formRef?.resetFields();
      this.formData = {
        detailId: null,
        farmerId: null,
        farmerName: '',
        idCard: '',
        amount: null,
        status: 0,
        paymentTime: null
      };
    }
  },
  
  created() {
    this.fetchData();
  }
};
</script>

<style scoped>
/* 基础容器样式 */
.payment-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 搜索栏样式 */
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 表格样式 */
.table-container {
  overflow-x: auto;
}

.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #333;
  text-align: center;
}

.el-table .cell {
  padding: 10px 8px;
  text-align: center;
}

/* 省略号样式 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

/* 状态标签样式 */
.el-tag.success {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border-color: rgba(103, 194, 58, 0.2);
}

.el-tag.warning {
  background-color: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
  border-color: rgba(230, 162, 60, 0.2);
}

/* 对话框底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9fafc;
  border-radius: 0 0 6px 6px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .el-table-column:not([fixed]) {
    min-width: 120px;
  }
}
</style>